﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DailyComics.Common.Utilities;

namespace DailyComics.Common.Model.CachingStrategies
{
  public class FileCacheStrategy : ICachingStrategy
  {
    private string path;

    public FileCacheStrategy(string path)
    {
      this.path = path;

      if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    }

    #region ICachingStrategy Members

    public void Add(DateTime date, byte[] image)
    {
      if (Contains(date)) return;

      var fileName = GetFilePath(date);

      using(Stream stream = File.Create(fileName))
      {
        BinaryWriter writer = new BinaryWriter(stream);
        writer.Write(image);
      }

    }

    public byte[] Get(DateTime date)
    {
      var fileName = GetFilePath(date);

      byte[] image;

      using (Stream stream = File.Open(fileName,  FileMode.Open, FileAccess.Read))
      {
        BinaryReader reader = new BinaryReader(stream);
        image = reader.ReadBytes((int)stream.Length);
      }

      return image;
    }

    public bool Contains(DateTime date)
    {
      var fileName = GetFileName(date);

      return Directory.GetFiles(path).Any(f => f.Contains(fileName));
    }

    public void Clear()
    {
      Directory.Delete("path", true);
    }

    #endregion

    private string GetFileName(DateTime date)
    {
      var part = DateHelper.ConvertToUnderScoreSeperatedDate(date);
      
      var fileName = string.Format("{0}.{1}", part, "jpg");

      return fileName; 
    }

    private string GetFilePath(DateTime date)
    {
      var filePath = Path.Combine(path, GetFileName(date));

      return filePath;
    }
    
  }
}
